<?php
namespace app\index\controller;

use think\Cookie;
use app\common\controller\HomeBase;
use app\common\model\Wenan as WenanModel;
use app\common\model\Images as ImagesModel;
use app\common\model\Search as SearchModel;

class Search extends HomeBase
{
    protected $images_model;
    protected $wenan_model;
    protected $search_model;

    protected function _initialize(){
        parent::_initialize();
        $this->wenan_model = new WenanModel;
        $this->images_model = new ImagesModel;
        $this->search_model = new SearchModel;
    }

    public function index(){
        if($this->request->isPost()){
            $data = $this->request->post();
            if(Cookie::has('search')){
                $cookie_value = Cookie::get('search');
                $cookie_value[] = $data['value'];
                Cookie::set('search',array_reverse(array_unique($cookie_value)));
            }else{
                Cookie::set('search',array($data['value']));
            }
            $result = $this->search_model->where('text',$data['value'])->find();
            if($result){
                $aa = $this->search_model->where('id',$result['id'])->setInc('num');
            }else{
                $search_data['text'] = $data['value'];
                $this->search_model->save($search_data);
            }

            if($data['type'] == 1){
                //文案
                // $result = $this->wenan_model->where('title|abstract' ,'like' ,'%'.$data['value'].'%')->paginate(16,false,['page' => $page]);
                // if(!$result) return json(['status' => -1 , 'error' => 'search error']);
                return json(['url' => '/index/lists/lists/keyword/'.$data['value']]);
            }else if ($data['type'] == 2) {
                //素材
                return json(['url' => '/index/pic_list/pic_list/keyword/'.$data['value']]);
            }
            // return $result;
        }
    }

    public function searchRan(){
        $rankings = $this->search_model->field('text,num')->limit(6)->order('num desc')->select();
        if(!$rankings) return json(['status' => -1,'error' => 'not rankings']);
        return json(['status' => 1 , 'msg' => 'ok' , 'rankings' => $rankings]);
    }
}